﻿using System;
using System.IO;
using System.Windows.Forms;

namespace Autoupdate.Common
{
    public static class Log
    {
        private static bool mMakePath = false;
        private static string mFileName = Application.StartupPath + "\\Log.txt";

        public static string FileName
        {
            get { return mFileName; }
            set
            {
                mFileName = value;
                mMakePath = false;
                MakePath();
            }
        }

        public static void WriteInfo(string section, string message)
        {
            MakePath();
            string content = "[ " + DateTime.Now.ToString() + " ][ Info ]-[" + section + "]: ";
            content += message;
            StreamWriter streamWriter = new StreamWriter(mFileName, true);
            streamWriter.WriteLine(content);
            streamWriter.Close();
        }

        public static void WriteWarning(string section, string message)
        {
            MakePath();
            string content = "[ " + DateTime.Now.ToString() + " ][ Warnning ]-[" + section + "]: ";
            content += message;
            StreamWriter streamWriter = new StreamWriter(mFileName, true);
            streamWriter.WriteLine(content);
            streamWriter.Close();
        }

        public static void WriteError(string section, string message)
        {
            MakePath();
            string content = "[ " + DateTime.Now.ToString() + " ][ Error ]-[" + section + "]: ";
            content += message;
            StreamWriter streamWriter = new StreamWriter(mFileName, true);
            streamWriter.WriteLine(content);
            streamWriter.Close();
        }

        static public void WriteCallStack()
        {
            MakePath();
            StreamWriter streamWriter = new StreamWriter(mFileName, true);
            streamWriter.WriteLine(new string('*', 78));
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
            System.Diagnostics.StackFrame[] sfs = st.GetFrames();
            for (int u = 1; u < sfs.Length; ++u)
            {
                System.Reflection.MethodBase mb = sfs[u].GetMethod();
                streamWriter.WriteLine("[CALL STACK][{0}]: {1}.{2}", u, mb.DeclaringType.FullName, mb.Name);
            }
            streamWriter.Close();
        }

        private static void MakePath()
        {
            if (mMakePath)
                return;
            string path = Path.GetDirectoryName(mFileName);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            mMakePath = true;
        }
    }
}
